<?php

namespace app\api\exception;

use Exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;
class ExceptionHandle extends Handle
{

    /**
     * 全局异常处理
     * @param Exception $e
     * @return \think\Response|\think\response\Json
     * Author: LCY<409028735@qq.com>
     * Time: 2020/11/25 17:20
     * Note:
     */
    public function render(Exception $e)
    {
        if ($e instanceof RegisterException) {
            //api接口的未注册异常处理
            return json(['code' => 10, 'msg' => $e->getMessage(), 'data' => ['openid' => $e->getOpenid()]], 200);
        } elseif ($e instanceof LoginException) {
            //api接口的未登录异常处理
            return json(['code' => 9, 'msg' => $e->getMessage(), 'data' => null], 200);
        } elseif ($e instanceof TokenException) {
            //api接口的token验证失败异常处理
            return json(['code' => 8, 'msg' => $e->getMessage(), 'data' => null], 200);
        } elseif ($e instanceof ServiceException) {
            //api接口的通用异常处理
            return json(['code' => 0, 'msg' => $e->getMessage(), 'data' => null], 200);
        } elseif ($e instanceof ValidateException) {
            //api接口的数据验证失败异常处理
            return json(['code' => 0, 'msg' => $e->getMessage(), 'data' => null], 200);
        } elseif ($e instanceof HttpException) {
            //HTTP相关错误
            $code = $e->getStatusCode();
            switch ($code) {
                case 401:
                    return json(['code' => 0, 'msg' => '还未登录'], 401);
                case 402:
                    return json(['code' => 0, 'msg' => 'token有误'], 402);
                case 403:
                    return json(['code' => 0, 'msg' => '无权访问'], 403);
                case 404:
                    return json(['code' => 0, 'msg' => '页面找不到'], 404);
                case 500:
                    return json(['code' => 0, 'msg' => '服务器错误'], 500);
                default:
                    return json(['code' => 0, 'msg' => '服务器错误'], 200);
            }
        }

        if (config('app_debug')) {
            return json(['code' => 0, 'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()], 200);
        } else {
            //记录日志
            recordExceptionInfo($e);
            return json(['code' => 0, 'msg' => '服务器错误'], 200);
        }
    }
}
